package tdd.xuchun.test.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import tdd.xuchun.test.model.Host;
import tdd.xuchun.test.model.Page;
import tdd.xuchun.test.model.Result;
import tdd.xuchun.test.service.IEasyNmonService;
import tdd.xuchun.test.service.IHostService;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 主机控制器
 * 
 * @author ZSL
 *
 */
@RestController

public class HostController{

	/**
	 * 注入主机业务服务
	 */
	@Autowired
	private IHostService hostService;
	@Autowired
	private IEasyNmonService easyNmonService;

	// 映射"/"请求
	@RequestMapping("/")
	public ModelAndView index(){
		return new ModelAndView("index",new HashMap());
	}

	// 映射"/"请求
	@RequestMapping("/host/host_add")
	public ModelAndView hostadd(){
		return new ModelAndView("host_add",new HashMap());
	}
	/**
	 * 查询单个主机详细信息
	 * 
	 * @return
	 */
	@RequestMapping("host/editpage")
	public ModelAndView findHost(Host host){
		Host rsHost = hostService.getHost(host);
        Map<String,Object> rsMap = new HashMap<String,Object>();
        rsMap.put("data", rsHost);
		return new ModelAndView("host_edit",rsMap);
	}
	

	/**
	 * 查询单个主机详细信息
	 * 
	 * @return
	 */
	@RequestMapping("host/copyaddpage")
	public ModelAndView findAddHost(Host host){
		Host rsHost = hostService.getHost(host);
        Map<String,Object> rsMap = new HashMap<String,Object>();
        rsMap.put("data", rsHost);
		return new ModelAndView("host_copyadd",rsMap);
	}
	
	/**
	 * 增加新主机
	 * 
	 * @return
	 */
	@RequestMapping("host/add")
	public Result addHost(Host host){
		hostService.addHost(host);
		return new Result();
	}
	
	/**
	 * 删除主机
	 * 
	 * @return
	 */
	@RequestMapping("host/del")
	public Result delHost(Host host){
		host = hostService.getHost(host);
		int code = easyNmonService.accessTheURL(host, "");
		if (code == 200) {
			easyNmonService.clearService(host);
		}
		hostService.delHost(host);
		return new Result();
	}
	
	/**
	 * 编辑主机
	 * 
	 * @return
	 */
	@RequestMapping("host/edit")
	public Result editHost(Host host){
		hostService.editHost(host);
		return new Result();
	}
	
	/**
	 * 模糊查询主机列表
	 * 
	 * @return
	 */
	@RequestMapping("host/getcond")
	public Page queryLikeHosts(int pageSize,int pageNum,Host host){
		Map<String,Object> cond=new HashMap<String,Object>();
		cond.put("pageSize", pageSize);
		cond.put("pageNum", pageNum);
		cond.put("host", host);
		Page page = hostService.queryLikeHosts(cond);
		return page;
	}

	/**
	 * 上传key文件
	 * @param file
	 * @return
	 */
	@RequestMapping("/upload")
	@ResponseBody
	public String upload(@RequestParam("file") MultipartFile file) {
		String fileName = file.getOriginalFilename();
		if(fileName.indexOf("\\") != -1){
			fileName = fileName.substring(fileName.lastIndexOf("\\"));
		}
		String filePath = "/tmp/"+IdUtil.simpleUUID()+"/";
		File targetFile = new File(filePath);
		if(!targetFile.exists()){
			targetFile.mkdirs();
		}
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(filePath+fileName);
			out.write(file.getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			return "上传失败";
		}
		//return "上传成功!|"+filePath+fileName;
		return "上传成功";
	}

	/**
	 * 下载主机模板文件
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@GetMapping(value = "/host/downloadTemplate")
	public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String templatePath = "templates/hostinfoTemplate.xlsx";
		String fileName = "easyNmonManagerTemplate.xlsx";
		fileName = new String((fileName).getBytes(), "ISO-8859-1");
		// 清除buffer缓存
		response.reset();
		response.setContentType("content-type:octet-stream;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);

		//文件路径
		ClassPathResource cpr = new ClassPathResource(templatePath);
		BufferedInputStream inputStream = new BufferedInputStream(cpr.getInputStream());

		ServletOutputStream out = response.getOutputStream();
		int b = 0;
		byte[] buffer = new byte[1024];
		while ((b = inputStream.read(buffer)) != -1) {
			//写到输出流(out)中
			out.write(buffer, 0, b);
		}
		inputStream.close();
		if (out != null) {
			out.flush();
			out.close();
		}
	}

	/**
	 * 上传主机模板
	 * @param file
	 * @return
	 */
	@RequestMapping("/host/importTemplate")
	@ResponseBody
	public JSONObject importTemplate(@RequestParam("file") MultipartFile file) {
		JSONObject json = new JSONObject();
		String fileName = file.getOriginalFilename();
		if(fileName.indexOf("\\") != -1){
			fileName = fileName.substring(fileName.lastIndexOf("\\"));
		}
		String filePath = "/tmp/"+IdUtil.simpleUUID()+"/";
		File targetFile = new File(filePath);
		if(!targetFile.exists()){
			targetFile.mkdirs();
		}
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(filePath+fileName);
			out.write(file.getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			json.put("msg","上传失败");
			return json;
		}
		ExcelReader reader = ExcelUtil.getReader(filePath+fileName);
		new File(filePath+fileName).deleteOnExit();
		List<Map<String,Object>> readAll = reader.readAll();
		for(int i=0;i<readAll.size();i++){
			Map  hostmap=readAll.get(i);
			Host host=new Host();
			host.setName(hostmap.get("主机名称")+"");
			host.setAddr(hostmap.get("IP")+"");
			host.setPort(Integer.parseInt(hostmap.get("SSH端口")+""));
			host.setUsername(hostmap.get("用户名")+"");
			host.setPassword(hostmap.get("密码")+"");
			host.setEznmonport(Integer.parseInt(hostmap.get("easyNmon监控端口")+""));
			host.setRemark(hostmap.get("备注")+"");
			try {
				hostService.addHost(host);
			} catch (Exception e){}
		}
		json.put("msg","导入成功");
		return json;
	}
}
